package com.hnust.service.impl;

import com.hnust.dao.StudentDao;
import com.hnust.dao.ClassDao;
import com.hnust.dao.QuestionDao;
import com.hnust.domain.*;
import com.hnust.domain.Class;
import com.hnust.domain.record.*;
import com.hnust.service.StudentService;
import com.hnust.util.IDUtil;
import com.hnust.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("studentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private ClassDao classDao;
    @Autowired
    private QuestionDao questionDao;


    //实体类转中间类
    @Override
    public List<MajorRecord> getMajor(String collegeId) {
        List<Major> majors=studentDao.getMajor(collegeId);
        List<MajorRecord> majorRecords=new ArrayList<>();
        try {
            for(Major major:majors){
                MajorRecord majorRecord=new MajorRecord();
                majorRecord.setMajorId(major.getMajId());
                majorRecord.setName(major.getName());
                majorRecords.add(majorRecord);
            }

            if (majorRecords.size()==0){
                return null;
            }else {
                return majorRecords;
            }

        }catch (Exception e){
            return null;
        }
    }

    @Override
    public String login(String account, String password) {
        Student student = null;
        try{
            student = studentDao.queryStudentByAccount(account);
            if(student==null){
                student = studentDao.queryStudentByEmail(account);
            }
        }catch (Exception e){
            return "登陆失败";
        }
        if(student==null) {
            return "账号/邮箱错误";
        }
        if(!student.getPassword().equals(password)) {
            return "密码错误";
        }
        return student.getStuId();
    }

    @Override
    public String register(String account, String alias, String mail, String password, String phoneNumber) {
        String id = IDUtil.getPrimaryKey();
        try {
            studentDao.addStudent(id, account, alias, "", null, phoneNumber, mail, password, null, null);
        }catch (Exception e){return "账号/邮箱/电话已存在";}
        return "注册成功";
    }

    @Override
    public StudentUpCaseRecord getStudent(String studentId, String token) {
            Student students = null;
            StudentUpCaseRecord studentRecord = new StudentUpCaseRecord();
            Map<String, String> map = null;
            String idInToken;
            String passwordInToken;
            try{
                map = JwtToken.verifyToken(token);
                idInToken = map.get("id");
                passwordInToken = map.get("password");
            }catch (Exception e){
                return null;
            }
            if(!idInToken.equals(studentId)){
                return null;
            }
            try{
                students = studentDao.queryStudentById(idInToken);
                if(students==null){
                    return null;
                }
            }catch (Exception e){
                return null;
            }
            //类型转换
            try {
                studentRecord.setStuId(students.getStuId());
                studentRecord.setAccount(students.getAccount());
                studentRecord.setAlias(students.getAlias());
                studentRecord.setCls(students.getClsId());
                studentRecord.setName(students.getName());
                studentRecord.setStuNumber(students.getStuNumber());
                studentRecord.setEMail(students.getEMail());
                studentRecord.setPhoNumber(students.getPhoNumber());
                studentRecord.setSchool(students.getSchool());
            }catch (Exception e){
                return studentRecord;
            }
            //获取班级表中数据
            try {
                Class classes = classDao.getClass(students.getClsId());
                studentRecord.setCollege(classes.getColId());
                studentRecord.setGrade(classes.getGrade());
                studentRecord.setMajor(classes.getMajId());
            }catch (Exception e){
                studentRecord.setCls(null);
                studentRecord.setCollege(null);
                studentRecord.setGrade(null);
                return studentRecord;
            }
        return studentRecord;
    }


    @Override
    public String changePassword(String studentID, String newPassword, String password, String token) {
        Map<String, String> map = null;
        try{
            map = JwtToken.verifyToken(token);
        }catch (Exception e){
            return "无效令牌";
        }
        String idInToken = map.get("id");
        String passwordInToken = map.get("password");
        if(!idInToken.equals(studentID)){
            return "用户不匹配";
        }
        Student student = null;
        try{
            student = studentDao.queryStudentById(idInToken);
        }catch (Exception e){
            return "用户不存在";
        }
        if(!student.getPassword().equals(password)){
            return "用户不匹配";
        }

        try{
            studentDao.modifyStudentById(student.getStuId(),student.getAlias(),student.getName(), student.getStuNumber(), student.getPhoNumber(), student.getEMail(), newPassword, student.getSchool(), student.getClsId());
        }catch (Exception e) {
            return "修改密码失败";
        }
        return "修改成功";
    }

    @Override
    @Transactional
    public String modifyStudentById(String studentId, StudentLowerCaseRecord studentRecord, String token){
        Map<String, String> map = null;
        try{
            map = JwtToken.verifyToken(token);
        }catch (Exception e){
            return "无效令牌";
        }
        String idInToken = map.get("id");
        String passwordInToken = map.get("password");
        if(!idInToken.equals(studentId)){
            return "用户不匹配";
        }
        Student student = null;
        try{
            student = studentDao.queryStudentById(idInToken);
            if(student.getStuId()==null){
                return "用户不存在";
            }
        }catch (Exception e){
            return "用户不存在";
        }

        if ("0".equals(studentRecord.getCls())){
            try{
                studentRecord.setCls("null");
                studentDao.modifyStudentClassNoneById(studentId,studentRecord.getAlias(),studentRecord.getName(), studentRecord.getStuNumber(), studentRecord.getPhoNumber(), studentRecord.getEMail(),passwordInToken,studentRecord.getSchool(),studentRecord.getCls());
//            classDao.modifyStudentClassById(studentRecord.getCls(),studentRecord.getGrade(),studentRecord.getMajor(),studentRecord.getCollege());
            }catch (Exception e) {
                return "修改信息失败";
            }
        }else {
             try{
                studentDao.modifyStudentById(studentId,studentRecord.getAlias(),studentRecord.getName(), studentRecord.getStuNumber(), studentRecord.getPhoNumber(), studentRecord.getEMail(),passwordInToken,studentRecord.getSchool(), studentRecord.getCls());
//            classDao.modifyStudentClassById(studentRecord.getCls(),studentRecord.getGrade(),studentRecord.getMajor(),studentRecord.getCollege());
            }catch (Exception e) {
               // System.out.println(e.getMessage());
                return "修改信息失败";
            }
        }

        return "修改成功";

    }

    @Override
    public List<College> getCollege(){
        try {
            List<College> colleges=studentDao.getCollege();
            return colleges;
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public List<Class> getClassList(String majorId){
        try {
            List<Class> classes=classDao.getClassList(majorId);
            if (classes.size()==0){
                return null;
            }else {
                return classes;
            }
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public String deleteQuestionRecord(String token,List<String> recordIDList){
        Map<String, String> map = null;
        try{
            map = JwtToken.verifyToken(token);
        }catch (Exception e){
            return "无效令牌";
        }
        String idInToken = map.get("id");

        Student student = null;
        try{
            student = studentDao.queryStudentById(idInToken);
        }catch (Exception e){
            return "用户不存在";
        }
        try {
            for (String queRecId:recordIDList ){
                int i = questionDao.deleteQuestionRecord(queRecId);
                if (i==0){
                    return "删除失败";
                }
            }
        }catch (Exception e){
            return "删除失败";
        }
        return "删除成功";
    }

    @Override
    public NewQuestionRecordRecord getQuestion(String questionID){
        Question questions =  questionDao.getQuestion(questionID);
        NewQuestionRecordRecord questionRecord = new NewQuestionRecordRecord();
        List<AlternativeAnswer> alternativeAnswer = questionDao.getQuestionAnswer(questionID);
        List<AlternativeAnswerRecord> alternativeAnswerRecords=new ArrayList<>();
        try {
            questionRecord.setContent(questions.getContent());
            questionRecord.setQueId(questions.getQueId());
            questionRecord.setType(questions.getQueTypId());
            questionRecord.setLevel(questions.getLevel());
            questionRecord.setAnalysis(questions.getAnalysis());
            questionRecord.setPoint(questions.getPoint());
        }catch (Exception e){
            return questionRecord;
        }
        try {
            for (AlternativeAnswer ansId :alternativeAnswer){
                AlternativeAnswerRecord alternativeAnswerRecord = new AlternativeAnswerRecord();
                alternativeAnswerRecord.setContent(ansId.getContent());
                if(ansId.getRight() == 1){
                    alternativeAnswerRecord.setRight(true);
                }
                if(ansId.getRight() == 2){
                    alternativeAnswerRecord.setRight(false);
                }
                alternativeAnswerRecords.add(alternativeAnswerRecord);
            }
            for (AlternativeAnswerRecord item:alternativeAnswerRecords){
                questionRecord.setAnswer(alternativeAnswerRecords);
            }
        }catch (Exception e){
            return questionRecord;
        }
        return questionRecord;
    }

    @Override
    public Map<String,Object> getRecordsList(String studentID,Integer recordType,Integer offset,Integer limit,String token){
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        if(!idInToken.equals(studentID)){
            return null;
        }
        Student student = null;
        try{
            student = studentDao.queryStudentById(idInToken);
        }catch (Exception e){
            return null;
        }
        List<QuestionRecord> questionRecord = questionDao.getRecordsList(studentID,recordType,limit,offset);
        List<QuestionRecordRecordRecord> questionRecordRecordRecordList = new ArrayList<>();
        Integer totalCount = questionDao.getRecordsListCount(studentID,recordType);
        Integer totalPage = (int)Math.ceil(totalCount/(double)limit);
        try {
            for (QuestionRecord item:questionRecord){
                QuestionRecordRecordRecord questionRecordRecordRecord = new QuestionRecordRecordRecord();
                questionRecordRecordRecord.setStuId(item.getStuId());
                questionRecordRecordRecord.setQueRecType(Integer.parseInt(item.getQueRecTypeId()));
                questionRecordRecordRecord.setQueRecId(item.getQueRecId());
                questionRecordRecordRecord.setQuenID(item.getQueId());
                questionRecordRecordRecord.setTime(String.valueOf(item.getTime()));
                questionRecordRecordRecord.setRight(item.getRight());
                Question question = questionDao.getRecordsQuestionList(item.getQueId());
                questionRecordRecordRecord.setLevel(question.getLevel());
                questionRecordRecordRecord.setQueContext(question.getContent());
                questionRecordRecordRecordList.add(questionRecordRecordRecord);

            }
        }catch (Exception e){
            return null;
        }
        result = new HashMap<>();
        result.put("totalPage",totalPage);
        result.put("recordList",questionRecordRecordRecordList);
        return result;
    }
}
